﻿using ERPSystem.Common.DTO;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using RBACCommon.API.RBACCommons.UserLogin;
using System.IdentityModel.Tokens.Jwt;
using System.Net.Mail;
using System.Net;
using System.Security.Claims;
using System.Text;
using Microsoft.EntityFrameworkCore;
using MySqlX.XDevAPI.Common;
using ERPSystem.Common.Domains.UserCommon;
using RBACCommon.API.Command.UserEmail;

namespace RBACCommon.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserReadController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly IConfiguration configuration;
        public UserReadController(IMediator mediator, IConfiguration configuration)
        {
            _mediator = mediator;
            this.configuration = configuration;
        }


        //RandomHelper aaa = new RandomHelper();
        //六位验证码
        static string cood = createrandom(6).ToLower();
        
        private static string createrandom(int codelengh)
        {
            int rep = 0;
            string str = string.Empty;
            long num2 = DateTime.Now.Ticks + rep;
            rep++;
            Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
            for (int i = 0; i < codelengh; i++)
            {
                char ch;
                int num = random.Next();
                if ((num % 2) == 0)
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                else
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                str = str + ch.ToString();
            }
            return str;
        }
        string cood2 = cood;
        /// <summary>
        /// 发送验证码
        /// </summary>
        [HttpPost]
        [AllowAnonymous]
        public ActionResult Code([FromQuery]string? email_r)
        {
            if (email_r.Contains("@"))
            {
                cood = createrandom(6).ToLower();

                //实例化一个发送邮件类。
                MailMessage mailMessage = new MailMessage();
                //发件人邮箱地址，方法重载不同，可以根据需求自行选择。
                mailMessage.From = new MailAddress("2846315639@qq.com");
                //收件人邮箱地址。
                mailMessage.To.Add(new MailAddress(email_r));
                //邮件标题。
                mailMessage.Subject = "这是你的验证码为：";
                //邮件内容。
                mailMessage.Body = "验证码：" + cood + "。此验证码只用于登录，请勿转发他人。";
                //实例化一个SmtpClient类。
                SmtpClient client = new SmtpClient();
                //在这里我使用的是qq邮箱，所以是smtp.qq.com，如果你使用的是126邮箱，那么就是smtp.126.com。
                client.Host = "smtp.qq.com";
                //使用安全加密连接。
                client.EnableSsl = true;
                //不和请求一块发送。
                client.UseDefaultCredentials = false;
                //验证发件人身份(发件人的邮箱，邮箱里的生成授权码);
                client.Credentials = new NetworkCredential("2846315639@qq.com", "mdmaixnrijtsddif");
                //发送
                client.Send(mailMessage);
                return Content("发送成功");
            }
            return Content("邮箱格式有误，请重新输入。");
        }
        /// <summary>
        /// 邮箱登录添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<ERPSystem.Common.DTO.Result> UserEmailCreate(UserEmailCreateCommand request, CancellationToken cancellationToken)
        {
            request.Code = cood;
            var result = await _mediator.Send(request);
            return result;

        }
        /// <summary>
        /// 666
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> UserEmailLogin(UserEmailLoginCommand request, CancellationToken cancellationToken)
        {
            var result = await _mediator.Send(request);
            var token = CreateTokenString();
            return Ok(new
            {
                result = result,
                token = token,
            });
        }


        /// <summary>
        /// 用户登录业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> UserLoginsQuery(UserLoginsQueryCommand request, CancellationToken cancellationToken)
        {
            var result =await _mediator.Send(request);
            var token = CreateTokenString();
            return Ok(new
            {
                result=result,
                token=token,
            });
        }




        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //读取配置文件
            var jwtSettings = configuration.GetSection("JWT").Get<JwtSettings>();
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SecurityKey);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名 hs256 加密算法
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //Claims是指用户的身份信息，例如用户名、角色、权限等，它们通常被包含在一个ClaimsPrincipal对象中。
            var claims = new[]
            {
                  new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                  new Claim("Email","pmandy@163.com"),
                  new Claim("Phone","123456"),
                  new Claim("UserId","1"),
           };

            // 生成Token
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,//发行者
                audience: jwtSettings.Audience,//受众
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
    public class LoginDto
    {
        public string? email_r { get; set; }
        public string? code { get; set; }
    }
}
